<!-- ERP-销售看板 -->
<template>
	<view class="page__content" style="background-color: #f9f9f9;height: 100%;overflow: auto;">
		<!-- 快捷菜单 -->
		<view class="commonBox">
			<view class="commonBox-title">
				<view class="commonBox-title-left">
					<text>快捷发起</text>
				</view>
				<view class="commonBox-title-right">
					<uni-icons fontFamily="CustomFontPlatform" :size="18" color="#51d0d0"
						@click="showPopUp()">{{'\ue657'}}</uni-icons>
				</view>
			</view>
			<view class="commonBox-content">
				<swiper :indicator-dots="true" class="swiper" :current="swiperIndex" @change="onSwiperChange">
					<swiper-item v-for="(page,index) in Math.ceil(shortcuts.length/8)" :key="index">
						<u-grid col="4">
							<u-grid-item
								:customStyle="{paddingTop:'10px',borderRadius:'5px',background:'linear-gradient(to bottom right, #F6F6F6, #FFFFFF)'}"
								v-for="(menu, menuIndex) in shortcuts.filter((item,index)=>index<(8*page) && index>=(page-1)*8)"
								:index="menuIndex" :key="menuIndex" @click="checkOutMenu(menu)">
								<uni-icons v-if="menu.CustomFont && menu.PIC_PH" :fontFamily="menu.CustomFont"
									:size="22"
									:color="menu.AP_Colour">{{ uni.$utils.toUniCode(menu.PIC_PH) }}</uni-icons>
								<uni-icons v-else fontFamily="CustomFontPlatform" :size="22"
									color="#3ace4b">{{ uni.$utils.toUniCode('&#xe62c;') }}</uni-icons>
								<text class="grid-text">{{ getAbbrev(menu.APFunName,7)	}}</text>
							</u-grid-item>
						</u-grid>
					</swiper-item>
				</swiper>
			</view>
		</view>

		<!-- 待办 -->
		<view class="commonBox">
			<view class="commonBox-title">
				<view class="commonBox-title-left">
					<u-tabs lineColor="#51d0d0"
						:activeStyle="{color:'#51d0d0',fontWeight:'500',transform:'scale(1.05)'}"
						:current="waitActiveCurrent" :list="todoCondition" @change="item=>switchTab('TODO',item)">
					</u-tabs>
				</view>
				<view class="commonBox-title-right">
				</view>
			</view>
			<view class="commonBox-content">
				<view class="scrollWrap">
					<view v-for="(item,index) in waitDataShow" @click="handleClick_wait(item)" :index="index"
						:key="index" class="scrollWrap-item">
						<view class="todoTop">
							<uni-icons fontFamily="CustomFontPlatform" :size="18"
								color="#3ace4b">{{ uni.$utils.toUniCode('&#xe62c;') }}</uni-icons>
							<text class="todoTop-text">{{item.Num}}</text>
						</view>
						<view class="todoBot">
							<text>{{getAbbrev(item.name,8)}}</text>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 实时数据 -->
		<view class="commonBox">
			<view class="commonBox-title">
				<view class="commonBox-title-left">
					<text>实时数据</text>
				</view>
				<view class="commonBox-title-right">
					<u-tabs lineColor="#51d0d0"
						:activeStyle="{color:'#51d0d0',fontWeight:'500',transform:'scale(1.05)'}" :list="realCondition"
						@change="item=>switchTab('REALTIME',item)">
					</u-tabs>
				</view>
			</view>
			<view class="commonBox-content">
				<view class="scrollWrap">
					<view v-for="(item,index) in realTimeData" :index="index" :key="index" class="scrollWrap-item">
						<view class="rtTop">
							<text class="rtTop-left">销</text>
							<text class="rtTop-right">{{item.Qty}}</text>
						</view>
						<view class="rtBot">
							<text>{{item.name}}</text>
							<text class="rtBot-right"><text
									style="color:#c9283a;margin-right: 3px;">{{item.Num}}</text>单</text>
						</view>
					</view>
				</view>
			</view>
		</view>

		<view class="commonBox">
			<view class="commonBox-title">
				<view class="commonBox-title-left">
					<text>销量</text>
				</view>
				<view class="commonBox-title-right">
					<u-tabs lineColor="#51d0d0"
						:activeStyle="{color:'#51d0d0',fontWeight:'500',transform:'scale(1.05)'}" :list="saleCondition"
						@change="item=>switchTab('SALE',item)">
					</u-tabs>
				</view>
			</view>
			<view class="commonBox-content">
				<view class="charts-box">
					<qiun-data-charts type="column" canvas-id="chart-sales" :canvas2d="true" :opts="opts"
						:chartData="chart1Data" :ontouch="true"></qiun-data-charts>
				</view>
			</view>
		</view>

		<view class="commonBox">
			<view class="commonBox-title">
				<view class="commonBox-title-left">
					<text>销售占比</text>
				</view>
				<view class="commonBox-title-right">
					<u-tabs lineColor="#51d0d0"
						:activeStyle="{color:'#51d0d0',fontWeight:'500',transform:'scale(1.05)'}" :list="propCondition"
						@change="item=>switchTab('PROP',item)">
					</u-tabs>
				</view>
			</view>
			<view class="commonBox-content">
				<view class="chart-box">
					<qiun-data-charts type="ring" canvas-id="chart1-sales" :opts="optsRing" :canvas2d="true"
						:chartData="chart2Data"></qiun-data-charts>
				</view>
			</view>
		</view>


	</view>
</template>

<script setup lang="ts" name="Sale">
	import { ref, onMounted, onUnmounted, computed, getCurrentInstance, nextTick, reactive } from 'vue';
	import { onLoad, onReady, onShow, onUnload } from "@dcloudio/uni-app";
	import useRequestQueue from '@/uni_modules/mc-ui/libs/http/UniversalRequestQueue';
	const { request, requestByUrl, onAllComplete, onError } = useRequestQueue();

	import { useMainStore, useInventoryStore, useUserStore, usePermissionStore } from '@/store';
	const inventoryStore = useInventoryStore();
	const mainStore = useMainStore();
	const userStore = useUserStore();
	const permissionStore = usePermissionStore();

	const currModuleID = 1;
	// 已配置全部快捷菜单(默认+自定义)
	let shortcuts = ref<any>([]);
	let module = ref<any>({})
	// 当前看板ID
	let currBoardID = 10;
	const swiperIndex = ref(0);
	// 定义持久化参数名
	const cacheKey = 'shortcuts_' + currBoardID;
	// 快捷菜单初始化
	const initShortcut = () => {
		const modules = mainStore.appConfigInfo.APPModules;
		const _module = modules.find((m : any) => m.ModuleID == currModuleID);
		if (!_module) {
			console.warn('未找到匹配的模块，currModuleID:', currModuleID);
			shortcuts.value = [];
			return;
		}
		module.value = _module;

		const cacheStr = uni.getStorageSync(cacheKey);
		// 默认快捷菜单
		const defaultShortcuts = module.value.shortcuts?.filter((item : any) => item.IsShortcut && item.KanBanID == currBoardID) || [];

		let _shortcuts = [];
		if (cacheStr) {
			try {
				const cachedShortcuts = JSON.parse(cacheStr);
				const nonDefaultShortcuts = compareMenus(cachedShortcuts, module.value.authPages || []);
				_shortcuts = [...defaultShortcuts, ...nonDefaultShortcuts];
			} catch (err) {
				console.error('快捷菜单缓存解析失败:', err);
				_shortcuts = defaultShortcuts;
			}
		} else {
			_shortcuts = defaultShortcuts;
		}
		shortcuts.value = _shortcuts;
		// 修正 swiperIndex 溢出
		const maxIndex = Math.ceil(shortcuts.value.length / 8) - 1;
		if (swiperIndex.value > maxIndex) {
			swiperIndex.value = maxIndex;
		}
		persistShortcut(shortcuts.value);
	};

	// 比较缓存非默认快捷菜单并返回
	const compareMenus = (oldMenu : any, newMenu : any) => {
		let _menus = oldMenu.filter((item : any) => {
			// 当前看板非默认菜单和其他看板所有菜单
			if ((item.KanBanID == currBoardID && !item.IsShortcut) || (item.KanBanID != currBoardID)) {
				return item;
			}
		})
		_menus.forEach((item : any, index : number) => {
			let flag = newMenu.some((m : any) => m.APPFunID == item.APPFunID);
			if (!flag) {
				_menus.splice(index, 1);
			}
		});

		return _menus;
	};
	// 持久化快捷菜单
	const persistShortcut = (shortcuts : any) => {
		uni.setStorageSync(cacheKey, JSON.stringify(shortcuts))
	};

	const initTabs = async () => {
		await getWaitData(); // 获取代办数据
		await getRealTimeData('本日');
		await getSalesVolume('本周');
		await getSaleProportion('本周');
	}
	let notApproveData = ref<any>([])
	let waitDataShow = ref<any>([])
	let waitData = ref<any>([])
	let realTimeData = ref<any>([]); // 实时数据
	const getWaitData = async () => {
		const ret = await request({
			config: {},
			url: 'APP_GetToDoByKanBan',
			method: 'POST',
			data: {
				KanBanID: currBoardID,
			}
		});
		if (ret.status == 200) {
			notApproveData.value = ret.data.ds;
			waitData.value = [...ret.data.ds1];

			// 默认初始展示代办
			waitDataShow.value = ret.data.ds;
		}
	};
	const getTimeRange = (type : any, format : any) => { // 传入字段，返回时间范围
		let now = new Date();
		let year = now.getFullYear();
		let month = now.getMonth() + 1; // 月份从0开始，所以需要加1
		let day = now.getDate();
		let weekDay = now.getDay(); // 0表示周日，1表示周一，以此类推

		switch (type) {
			case 'day':
				return [uni.$utils.dateFormat(new Date(year, month - 1, day, 0, 0, 0), format), uni.$utils.dateFormat(new Date(
					year, month - 1, day, 23, 59, 59), format)];
			case 'week':
				let startOfWeek = new Date(year, month - 1, day - weekDay, 0, 0, 0);
				let endOfWeek = new Date(year, month - 1, day + (6 - weekDay), 23, 59, 59);
				return [uni.$utils.dateFormat(startOfWeek, format), uni.$utils.dateFormat(endOfWeek, format)];
			case 'month':
				return [uni.$utils.dateFormat(new Date(year, month - 1, 1, 0, 0, 0), format), uni.$utils.dateFormat(new Date(
					year, month, 0, 23, 59, 59), format)];
			case 'year':
				return [uni.$utils.dateFormat(new Date(year, 0, 1, 0, 0, 0), format), uni.$utils.dateFormat(new Date(year, 11,
					31, 23, 59, 59), format)];
			default:
				throw new Error('Invalid type');
		}
	};
	// 实时数据
	let realCondition = [{
		name: '本日'
	}, {
		name: '本月'
	}];
	// 获取实时数据
	const getRealTimeData = async (name : string) => {
		const type = name === '本日' ? 'day' : name === '本月' ? 'month' : null;
		const dateRange = getTimeRange(type, 'yyyy-MM-dd');
		const ret = await request({
			config: {
				baseURL: mainStore.appConfigInfo.IPAgreement + mainStore.appConfigInfo.serverIP + "/Frame/SqlData?cmdname="
			},
			url: 'PlatForm_XSNum',
			method: 'POST',
			data: {
				FSDate: dateRange[0],
				FEDate: dateRange[1]
			}
		});
		if (ret.status == 200) {
			realTimeData.value = ret.data.ds;
		}
	};



	// 销售切换条件
	const saleCondition = [{
		name: '本周'
	}, {
		name: '本月'
	}, {
		name: '本年'
	}];
	let chart1Data = ref<any>({});
	let opts = {
		touchMoveLimit: 24,
		enableScroll: true,
		xAxis: {
			disableGrid: true,
			scrollShow: true,
			itemCount: 4
		}
	};
	// 获取销量
	const getSalesVolume = async (name : any) => {
		const type = name === '本周' ? 'week' : name === '本月' ? 'month' : name === '本年' ? 'year' : null;
		const ret = await request({
			config: {
				baseURL: mainStore.appConfigInfo.IPAgreement + mainStore.appConfigInfo.serverIP + "/Frame/SqlData?cmdname="
			},
			url: 'PlatForm_XSQty',
			method: 'POST',
			data: {
				FType: type
			}
		});
		if (ret.status == 200) {
			let data = JSON.parse(JSON.stringify(ret.data.ds));
			let newData = fillMissingTimeData(name, data);
			chart1Data.value = {
				categories: newData['name'],
				series: [{
					name: '销售金额',
					data: newData['Money']
				}, {
					name: '销售数量',
					data: newData['Qty']
				}]
			}
		}
	};
	const fillMissingTimeData = (timeRange : any, dataArray : any) => {
		let result = {
			name: [],
			Qty: [],
			Money: []
		} as any;

		// 根据时间范围初始化 result 数组
		let currentDate = new Date();
		if (timeRange === '本周') {
			let startOfWeek = currentDate.getDate() - currentDate.getDay();
			for (let i = startOfWeek; i <= currentDate.getDate(); i++) {
				let date = new Date(currentDate.getFullYear(), currentDate.getMonth(), i);

				let formattedDate = (date.getMonth() + 1).toString().padStart(2, '0') + '-' + date.getDate()
					.toString().padStart(2, '0');
				let existingItem = dataArray.find((item : any) => item.name === formattedDate);
				if (existingItem) {
					result.name.push(existingItem.name);
					result.Qty.push(existingItem.Qty);
					result.Money.push(existingItem.Money);
				} else {
					result.name.push(formattedDate);
					result.Qty.push(0);
					result.Money.push(0);
				}
			}
		} else if (timeRange === '本月') {
			for (let i = 1; i <= currentDate.getDate(); i++) {
				let date = new Date(currentDate.getFullYear(), currentDate.getMonth(), i);
				let formattedDate = (date.getMonth() + 1).toString().padStart(2, '0') + '-' + date.getDate()
					.toString().padStart(2, '0');
				let existingItem = dataArray.find((item : any) => item.name === formattedDate);
				if (existingItem) {
					result.name.push(existingItem.name);
					result.Qty.push(existingItem.Qty);
					result.Money.push(existingItem.Money);
				} else {
					result.name.push(formattedDate);
					result.Qty.push(0);
					result.Money.push(0);
				}
			}
		} else if (timeRange === '本年') {
			for (let i = 0; i <= currentDate.getMonth(); i++) {
				let date = new Date(currentDate.getFullYear(), i, 1);
				let formattedDate = i + 1;
				let existingItem = dataArray.find((item : any) => item.name === formattedDate);
				if (existingItem) {
					result.name.push(existingItem.name + '月');
					result.Qty.push(existingItem.Qty);
					result.Money.push(existingItem.Money);
				} else {
					result.name.push(formattedDate + '月');
					result.Qty.push(0);
					result.Money.push(0);
				}
			}
		}

		return result;
	};


	// 获取销售占比
	const propCondition = [{
		name: '本周'
	}, {
		name: '本月'
	}, {
		name: '本年'
	}];
	let chart2Data = ref<any>({});
	const optsRing = {
		padding: [5, 5, 5, 5],
		enableScroll: false,
		legend: {
			show: true,
			position: "left",
			lineHeight: 25
		},
		title: {
			name: "",
		},
		subtitle: {
			name: "",
		},
		extra: {
			ring: {
				ringWidth: 60,
				activeOpacity: 0.5,
				activeRadius: 10,
				offsetAngle: 0,
				labelWidth: 15,
				border: false,
				borderWidth: 3,
				borderColor: "#FFFFFF"
			}
		}
	};
	const getSaleProportion = async (name : string) => {
		const type = name === '本周' ? 'week' : name === '本月' ? 'month' : name === '本年' ? 'year' : null;

		const ret = await request({
			config: {
				baseURL: mainStore.appConfigInfo.IPAgreement + mainStore.appConfigInfo.serverIP + "/Frame/SqlData?cmdname="
			},
			url: 'PlatForm_XSRatio',
			method: 'POST',
			data: {
				FType: type
			}
		});
		if (ret.status == 200) {

			let data = ret.data.ds.map((item : any) => {
				return {
					...item,
					name: uni.$utils.isEmpty(item.name) ? "" : item.name,
					value: uni.$utils.isEmpty(item.Rate) ? 0 : item.Rate
				}
			});

			chart2Data.value = {
				series: [{
					data: data
				}]
			}

		}
	};


	// 待办
	let waitActiveCurrent = ref(0);
	const todoCondition = [{
		name: '待办'
	}, {
		name: '待审核'
	}];

	// 条件切换
	const switchTab = (switchType : any, item : any) => {
		switch (switchType) {
			case 'TODO':
				waitActiveCurrent.value = item.index;
				waitDataShow.value = item.name === '待办' ? notApproveData.value : waitData.value;
				break;
			case 'REALTIME':
				getRealTimeData(item.name);
				break;
			case 'SALE':
				getSalesVolume(item.name);
				break;
			case 'PROP':
				getSaleProportion(item.name);
				break;
			default:
				break;
		}
	}
	const handleClick_wait = (data : any) => {
		let _newData = uni.$utils.deepClone(data)
		_newData['APFunName'] = '';
		_newData['Para'] = '';
		let _path = '';
		let _moduleName = '';
		if (_newData && _newData['Url']) {
			const [urlPath, queryString] = _newData['Url'].split('?');
			_path = urlPath;

			if (queryString) {
				// 直接搜索并提取moduleName的值  
				const params = queryString.split('&');
				for (const param of params) {
					const [key, value] = param.split('=');
					if (key === 'moduleName') {
						_moduleName = decodeURIComponent(value);
						break; // 找到后退出循环  
					}
				}
			}
		}
		_newData['APFunName'] = _moduleName;
		_newData['Para'] = _moduleName;

		inventoryStore.Menu = _newData;

		let theType = waitActiveCurrent.value == 0 ? "wait" : "audit";
		uni.navigateTo({
			url: _path + "?type=" + theType
		})

	};





	// 事件触发
	// 显示快捷菜单设置
	const showPopUp = () => {
		let data = {
			currModuleID: currModuleID,
			currBoardID: currBoardID,
			currModule: module.value,
			currShortcut: shortcuts.value
		};

		mainStore.BaseScreenParm = data;

		uni.navigateTo({
			url: '/commonPage/kanban/shortcutSetting/shortcutSetting',
			events: {
				refreshShortcut() {

					initShortcut();
				}
			}
		})

	}
	const onSwiperChange = (e : any) => {
		swiperIndex.value = e.detail.current;
	}
	let organizedData = ref([]);
	let TabbarData = ref([]);
	// 跳转当前菜单页面
	const checkOutMenu = (menu : any) => {
		let filterData = mainStore.appConfigInfo.APPModules.filter((item : any) => item.ModuleName == menu.APPTypeName);
		permissionStore.moduleInfoAll = organizedData.value;
		permissionStore.moduleTabbar = TabbarData.value;
		permissionStore.activeModule = filterData[0];

		inventoryStore.Menu = menu;
		// 页面跳转待配置
		uni.navigateTo({
			url: menu.AP_Link
		});

	};

	// 数据映射
	// 菜单字数截取(菜单名称,截取字数)
	const getAbbrev = (menuName : any, num : any) => {
		let result = '';
		if (menuName.length > num) {
			result = menuName.substring(0, num);
		} else {
			result = menuName;
		}
		return result;
	};



	onMounted(async () => {
		await nextTick()
		setTimeout(() => {

			// 快捷菜单初始化
			initShortcut();
			initTabs();
		}, 500);
	})
</script>

<style lang="scss" scoped>
	$h-padding: 5px;
	$v-padding: 10px;
	$radius: 5px;

	.commonBox {
		display: flex;
		flex-direction: column;
		padding: $v-padding $h-padding;
		background-color: #ffffff;
		margin-bottom: $v-padding;
		border-radius: $radius;

		&-title {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 0 $h-padding $v-padding $h-padding;

			&-left {
				display: flex;
				justify-content: flex-start;
				align-items: center;
				width: 150rpx;
				font-size: 14px;
				font-weight: 500;
			}

			&-right {
				display: flex;
				justify-content: flex-end;
				align-items: center;
				width: 100rpx;
			}
		}

		&-content {
			display: flex;
			flex-direction: column;

			// 快捷菜单宫格
			.grid-text {
				font-size: 12px;
				color: #909399;
				padding: 5px 0 10px 0;
				box-sizing: border-box;
			}

			// 待办/实时数据横向滚动
			.scrollWrap {
				display: flex;
				flex-direction: column;
				flex-wrap: wrap;
				align-content: flex-start;
				max-height: 180px;
				overflow-y: hidden;
				overflow-x: auto;

				&-item {
					width: 35vw;
					height: 80px;
					display: flex;
					flex-direction: column;
					background: linear-gradient(to bottom right, #F6F6F6, #FFFFFF);
					border-radius: 5px;
					justify-content: center;
					align-items: center;

					.todoBot {
						display: flex;
						justify-content: flex-start;
						align-items: center;
						width: 100%;
						padding: 5px 10px;
						color: #909399;
						font-size: 14px;
					}



					// 实时数据
					.rtTop {
						display: flex;
						justify-content: center;
						align-items: center;
						padding: 10px 0;
						font-size: 18px;
						font-weight: 500;

						&-left {
							display: flex;
							justify-content: center;
							align-items: center;
							color: rgba(108, 148, 255, 1);
							background: rgba(108, 148, 255, .11);
							width: 36px;
							height: 36px;
							line-height: 36px;
							border-radius: 18px;
						}

						&-right {
							margin-left: 20px;
						}
					}

					.rtBot {
						display: flex;
						justify-content: space-between;
						font-size: 14px;
						color: #909399;

						&-right {
							margin-left: 10px;
						}
					}
				}
			}

			// 图表
			.charts-box {
				width: 100%;
				height: 300px;
			}
		}
	}
</style>